package com.ruoyi.repair.service.impl;

import java.util.Date;
import java.util.List;

import com.ruoyi.repair.domain.TFaultReport;
import com.ruoyi.repair.domain.TRepairRecord;
import com.ruoyi.asset.service.ITAssetService;
import com.ruoyi.asset.domain.TAsset;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.repair.mapper.TWorkOrderMapper;
import com.ruoyi.repair.domain.TWorkOrder;
import com.ruoyi.repair.domain.dto.WorkOrderQueryDTO;
import com.ruoyi.repair.service.ITWorkOrderService;
import com.ruoyi.repair.service.ITFaultReportService;
import com.ruoyi.repair.service.ITRepairRecordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 维修单Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-09-24
 */
@Service
public class TWorkOrderServiceImpl implements ITWorkOrderService 
{
    private static final Logger log = LoggerFactory.getLogger(TWorkOrderServiceImpl.class);
    
    @Autowired
    private TWorkOrderMapper tWorkOrderMapper;

    @Autowired
    private ITFaultReportService tFaultReportService;
    
    @Autowired
    private ITAssetService tAssetService;
    
    @Autowired
    private ITRepairRecordService tRepairRecordService;

    /**
     * 查询维修单
     * 
     * @param workNo 维修单主键
     * @return 维修单
     */
    @Override
    public TWorkOrder selectTWorkOrderByWorkNo(String workNo)
    {
        return tWorkOrderMapper.selectTWorkOrderByWorkNo(workNo);
    }

    /**
     * 查询维修单列表
     * 
     * @param tWorkOrder 维修单
     * @return 维修单
     */
    @Override
    public List<TWorkOrder> selectTWorkOrderList(TWorkOrder tWorkOrder)
    {
        return tWorkOrderMapper.selectTWorkOrderList(tWorkOrder);
    }

    /**
     * 根据DTO查询维修单列表
     * 
     * @param queryDTO 查询DTO
     * @return 维修单集合
     */
    @Override
    public List<TWorkOrder> selectTWorkOrderListByDTO(WorkOrderQueryDTO queryDTO)
    {
        return tWorkOrderMapper.selectTWorkOrderListByDTO(queryDTO);
    }

    /**
     * 新增维修单
     * 
     * @param tWorkOrder 维修单
     * @return 结果
     */
    @Override
    public int insertTWorkOrder(TWorkOrder tWorkOrder)
    {
        return tWorkOrderMapper.insertTWorkOrder(tWorkOrder);
    }

    /**
     * 修改维修单
     * 
     * @param tWorkOrder 维修单
     * @return 结果
     */
    @Override
    public int updateTWorkOrder(TWorkOrder tWorkOrder)
    {
        int result = tWorkOrderMapper.updateTWorkOrder(tWorkOrder);
        
        // 同步更新故障报修状态
        if (result > 0 && tWorkOrder.getRptNo() != null) {
            try {
                // 根据维修单状态更新故障报修状态
                String faultReportStatus = null;
                if ("PENDING_EXEC".equals(tWorkOrder.getStatusCode())) {
                    // 接取维修任务时，故障报修状态变为"维修中"
                    faultReportStatus = "IN_REPAIR";
                } else if ("PENDING_ASSIGN".equals(tWorkOrder.getStatusCode())) {
                    // 退回维修任务时，故障报修状态保持"待分配"
                    faultReportStatus = "PENDING_ASSIGN";
                } else if ("ASSIGNED".equals(tWorkOrder.getStatusCode())) {
                    // 指派维修任务时，故障报修状态保持"维修中"
                    faultReportStatus = "IN_REPAIR";
                } else if ("CONFIRMED".equals(tWorkOrder.getStatusCode())) {
                    // 确认维修时，故障报修状态变为"已确认"
                    faultReportStatus = "CONFIRMED";
                } else if ("IN_PROGRESS".equals(tWorkOrder.getStatusCode())) {
                    // 开始维修时，创建开始记录
                    createStartRecord(tWorkOrder);
                } else if ("EXTRA_PROCESSING".equals(tWorkOrder.getStatusCode())) {
                    // 追加工时，更新故障报修状态为追加工中
                    faultReportStatus = "EXTRA_PROCESSING";
                }
                
                // 处理接取维修任务时的记录创建
                if ("PENDING_EXEC".equals(tWorkOrder.getStatusCode())) {
                    // 接取维修任务时，创建接取记录
                    createAcceptRecord(tWorkOrder);
                }
                
                if (faultReportStatus != null) {
                    // 更新故障报修状态
                    tFaultReportService.updateFaultReportStatus(tWorkOrder.getRptNo(), faultReportStatus);
                }
            } catch (Exception e) {
                // 记录日志但不影响维修单更新
                log.error("同步故障报修状态失败: {}", e.getMessage(), e);
            }
        }
        
        return result;
    }

    /**
     * 恢复原始状态
     * 
     * @param tWorkOrder 维修单
     * @param originalStatus 原始状态
     * @return 结果
     */
    public int restoreOriginalStatus(TWorkOrder tWorkOrder, String originalStatus) {
        tWorkOrder.setStatusCode(originalStatus);
        return tWorkOrderMapper.updateTWorkOrder(tWorkOrder);
    }

    /**
     * 批量删除维修单
     * 
     * @param workNos 需要删除的维修单主键集合
     * @return 结果
     */
    @Override
    public int deleteTWorkOrderByWorkNos(String[] workNos)
    {
        return tWorkOrderMapper.deleteTWorkOrderByWorkNos(workNos);
    }

    /**
     * 删除维修单信息
     * 
     * @param workNo 维修单主键
     * @return 结果
     */
    @Override
    public int deleteTWorkOrderByWorkNo(String workNo)
    {
        return tWorkOrderMapper.deleteTWorkOrderByWorkNo(workNo);
    }
    
    /**
     * 更新资产状态为正常
     * 
     * @param rptNo 报修单号
     */
    private void updateAssetStatusToNormal(String rptNo) {
        try {
            // 通过报修单号获取故障报修信息
            TFaultReport faultReport = tFaultReportService.selectTFaultReportByReportNo(rptNo);
            if (faultReport != null && faultReport.getAssetNo() != null) {
                // 获取资产信息
                TAsset asset = tAssetService.selectTAssetByAssetNo(faultReport.getAssetNo());
                if (asset != null) {
                    // 更新资产状态为正常 (ASSET_STATUS_001)
                    asset.setStatusCode("ASSET_STATUS_001");
                    tAssetService.updateTAsset(asset);
                }
            }
        } catch (Exception e) {
            // 更新资产状态失败
        }
    }
    
    /**
     * 创建维修履历记录
     * 
     * @param tWorkOrder 维修单
     */
    private void createRepairRecord(TWorkOrder tWorkOrder) {
        try {
            // 通过报修单号获取故障报修信息
            TFaultReport faultReport = tFaultReportService.selectTFaultReportByReportNo(tWorkOrder.getRptNo());
            if (faultReport != null) {
                // 创建维修履历记录
                TRepairRecord repairRecord = new TRepairRecord();
                repairRecord.setWorkNo(tWorkOrder.getWorkNo());
                repairRecord.setStepName("维修完成");
                
                // 动态生成描述
                StringBuilder description = new StringBuilder();
                description.append("设备维修完成");
                
                if (tWorkOrder.getFaultCause() != null && !tWorkOrder.getFaultCause().trim().isEmpty()) {
                    description.append("，故障原因：").append(tWorkOrder.getFaultCause());
                }
                
                if (tWorkOrder.getCountermeasure() != null && !tWorkOrder.getCountermeasure().trim().isEmpty()) {
                    description.append("，处理措施：").append(tWorkOrder.getCountermeasure());
                }
                
                description.append("，设备状态已恢复正常");
                
                repairRecord.setDescription(description.toString());
                repairRecord.setOperatorId(tWorkOrder.getAssigneeId()); // 维修人员ID
                
                // 设置合理的维修时间
                Date now = new Date();
                Date startTime = tWorkOrder.getStartTime();
                Date endTime = tWorkOrder.getEndTime();
                
                // 如果开始时间为空，使用创建时间作为开始时间
                if (startTime == null) {
                    startTime = tWorkOrder.getCreatedAt() != null ? tWorkOrder.getCreatedAt() : now;
                }
                
                // 如果结束时间为空，使用当前时间作为结束时间
                if (endTime == null) {
                    endTime = now;
                }
                
                // 确保结束时间不早于开始时间
                if (endTime.before(startTime)) {
                    endTime = new Date(startTime.getTime() + 30 * 60 * 1000); // 开始时间后30分钟
                }
                
                repairRecord.setStartTime(startTime);
                repairRecord.setEndTime(endTime);
                repairRecord.setResult("SUCCESS");
                repairRecord.setIsDelete(0);
                repairRecord.setCreatedAt(new Date());
                repairRecord.setUpdatedAt(new Date());
                
                // 保存维修履历记录
                tRepairRecordService.insertTRepairRecord(repairRecord);
            }
        } catch (Exception e) {
            // 创建维修履历记录失败
        }
    }
    
    /**
     * 创建接取维修任务记录
     * 
     * @param tWorkOrder 维修单
     */
    private void createAcceptRecord(TWorkOrder tWorkOrder) {
        try {
            // 获取故障报修信息以生成更详细的描述
            TFaultReport faultReport = tFaultReportService.selectTFaultReportByReportNo(tWorkOrder.getRptNo());
            
            TRepairRecord repairRecord = new TRepairRecord();
            repairRecord.setWorkNo(tWorkOrder.getWorkNo());
            repairRecord.setStepName("接取任务");
            
            // 动态生成描述
            StringBuilder description = new StringBuilder();
            description.append("维修人员接取了维修任务");
            
            if (faultReport != null && faultReport.getAssetName() != null) {
                description.append("，设备：").append(faultReport.getAssetName());
            }
            
            if (faultReport != null && faultReport.getFaultDescription() != null && !faultReport.getFaultDescription().trim().isEmpty()) {
                description.append("，故障描述：").append(faultReport.getFaultDescription());
            }
            
            description.append("，准备开始维修工作");
            
            repairRecord.setDescription(description.toString());
            repairRecord.setOperatorId(tWorkOrder.getAssigneeId());
            repairRecord.setStartTime(new Date());
            repairRecord.setEndTime(new Date());
            repairRecord.setResult("SUCCESS");
            repairRecord.setIsDelete(0);
            repairRecord.setCreatedAt(new Date());
            repairRecord.setUpdatedAt(new Date());
            
                tRepairRecordService.insertTRepairRecord(repairRecord);
            } catch (Exception e) {
                // 创建接取任务记录失败
            }
    }
    
    /**
     * 创建开始维修记录
     * 
     * @param tWorkOrder 维修单
     */
    private void createStartRecord(TWorkOrder tWorkOrder) {
        try {
            // 获取故障报修信息以生成更详细的描述
            TFaultReport faultReport = tFaultReportService.selectTFaultReportByReportNo(tWorkOrder.getRptNo());
            
            TRepairRecord repairRecord = new TRepairRecord();
            repairRecord.setWorkNo(tWorkOrder.getWorkNo());
            repairRecord.setStepName("开始维修");
            
            // 动态生成描述
            StringBuilder description = new StringBuilder();
            description.append("维修人员开始执行维修工作");
            
            if (faultReport != null && faultReport.getAssetName() != null) {
                description.append("，设备：").append(faultReport.getAssetName());
            }
            
            if (faultReport != null && faultReport.getFaultTypeName() != null) {
                description.append("，故障类型：").append(faultReport.getFaultTypeName());
            }
            
            description.append("，正在分析故障原因");
            
            repairRecord.setDescription(description.toString());
            repairRecord.setOperatorId(tWorkOrder.getAssigneeId());
            repairRecord.setStartTime(new Date());
            repairRecord.setEndTime(null);
            repairRecord.setResult("IN_PROGRESS");
            repairRecord.setIsDelete(0);
            repairRecord.setCreatedAt(new Date());
            repairRecord.setUpdatedAt(new Date());
            
                tRepairRecordService.insertTRepairRecord(repairRecord);
            } catch (Exception e) {
                // 创建开始维修记录失败
            }
    }
}